//
//  UIImageView+Gif.m
//  ZFGifDecoderDemo
//
//  Created by 赵梁 on 2016/12/13.
//  Copyright © 2016年 zify. All rights reserved.
//

#import "UIImageView+ZF_Gif.h"

#import "ZFGifDecoder.h"
#import "ZFGifFrame.h"

@implementation UIImageView (ZF_Gif)

- (void)zf_animationGifWithNamed:(NSString *)gifImageName endWithImage:(UIImage*)endImage withRepeatCount:(NSUInteger)repeatCount
{
    ZFGifDecoder *gifDecoder = [ZFGifDecoder decoderWithGIFNamed:gifImageName];
    NSArray<ZFGifFrame*> *gifImages = [gifDecoder contentImages];
    
    NSTimeInterval duration = 0;
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:gifImages.count];
    for (ZFGifFrame *gifFrame in gifImages) {
        [images addObject:gifFrame.image];
        
        duration += gifFrame.duration;
    }
    self.animationImages = images; //动画图片数组
    self.animationDuration = duration; //执行一次完整动画所需的时长
    self.animationRepeatCount = repeatCount; //动画重复次数
    [self startAnimating];
    
    if (endImage) {
        self.layer.contents = (id)[endImage CGImage];
    }
}

- (void)zf_animationOnceGifWithNamed:(NSString *)gifImageName endWithImage:(UIImage *)endImage completion:(void (^ __nullable)(void))completion
{
    [self zf_animationGifWithNamed:gifImageName endWithImage:endImage withRepeatCount:1];
    
    if (self.isAnimating) {
        [self stopAnimating];
    }
    [self startAnimating];
    
    if (completion) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((self.animationDuration+0.1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            completion();
        });
    }
}

- (void)zf_animationGifWithData:(NSData *)data endWithImage:(UIImage *)endImage withRepeatCount:(NSUInteger)repeatCount
{
    ZFGifDecoder *gifDecoder = [ZFGifDecoder decoderWithData:data];
    NSArray<ZFGifFrame*> *gifImages = [gifDecoder contentImages];
    
    NSTimeInterval duration = 0;
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:gifImages.count];
    for (ZFGifFrame *gifFrame in gifImages) {
        [images addObject:gifFrame.image];
        
        duration += gifFrame.duration;
    }
    self.animationImages = images; //动画图片数组
    self.animationDuration = duration; //执行一次完整动画所需的时长
    self.animationRepeatCount = repeatCount; //动画重复次数
    [self startAnimating];
    
    if (endImage) {
        self.layer.contents = (id)[endImage CGImage];
    }
}

- (void)zf_animationOnceGifWithData:(NSData *)data endWithImage:(UIImage *)endImage completion:(void (^)(void))completion
{
    [self zf_animationGifWithData:data endWithImage:endImage withRepeatCount:1];
    
    if (self.isAnimating) {
        [self stopAnimating];
    }
    [self startAnimating];
    
    if (completion) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((self.animationDuration+0.1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            completion();
        });
    }
}

@end
